﻿using mozhi.smarterp.Finance.Banks.Repository;
using mozhi.smarterp.Finance.Basedatas.Repository;
using Mozhi.Abp.Domain.BasicData.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Finance.Banks
{
    public class BankAccountManager : DomainService
    {
        private IBankAccountRepository _repository;
        private IGuidGenerator _guidGenerator;
        private ICurrencyRepository _currencyRepository;
        private IBankTypeRepository _bankTypeRepository;

        public BankAccountManager(IBankAccountRepository repository , IGuidGenerator guidGenerator, ICurrencyRepository currencyRepository, IBankTypeRepository bankTypeRepository)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
            _currencyRepository = currencyRepository;
            _bankTypeRepository = bankTypeRepository;
        }

        public async Task<BankAccount> GetAsync(Guid? id, string name, Guid currencyId, Guid? bankTypeId, string number, bool enableReconcile, string brachInfo)
        {
            await Validate(id, number , name, currencyId, bankTypeId);

            BankAccount bankAccount;

            if (id.HasValue)
            {
                bankAccount = await _repository.GetAsync(id.Value);

                if (bankAccount == null)
                    throw new UserFriendlyException("银行账号不存在", "100000");

                bankAccount.Change(name , currencyId , bankTypeId , number , enableReconcile ,brachInfo);
            }
            else
            {
                bankAccount = new BankAccount(_guidGenerator.Create(), name, currencyId, bankTypeId, number, enableReconcile, brachInfo);
            }

            return bankAccount;
        }


        public async Task Validate(Guid? id , string number , string name , Guid currencyId , Guid? bankTypeId)
        {
            var count = await _repository.GetCountAsync(null, number, null, id) + await _repository.GetCountAsync(null, null, name, id);

            if (count > 0)
                throw new UserFriendlyException("名称已经存在", "100000");

            var currency = await _currencyRepository.GetAsync(currencyId);

            if (currency == null)
                throw new UserFriendlyException("币别不存在", "100000");

            currency.Validate();

            if (bankTypeId.HasValue)
            {
                var bankType = await _bankTypeRepository.FindAsync(bankTypeId.Value);

                if (bankType == null)
                    throw new UserFriendlyException("银行类型不存在", "100000");
            }
           
        }
    }
}
